package user

import (
	"context"
	"fmt"
	"math"
	"net/http"
	"regexp"
	"strings"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

func getDefaultAddress(uid int) (address, phone string) { // 获取默认地址信息
	var NewAddress model.Address
	if ret := global.App.DB.Where("user_id = ?", uid).Where("isdefault = ?", 1).Find(&NewAddress); ret.RowsAffected == 0 {
		address = "Null"
		phone = "Null"
	} else {
		address = fmt.Sprintf("%s ( %s 收 ) %s", NewAddress.Addr, NewAddress.Receiver, NewAddress.Phone)
		phone = NewAddress.Phone
	}
	return
}

func getHistoryGoodList(ctx context.Context, uid int) ([]model.GoodsSKU, error) { // 获取用户浏览的历史记录
	// 存储类型：key:list,后浏览的放在列表后面，页面显示的时候，后浏览的放在goods_list的前面
	historyKey := fmt.Sprintf("browsingHistory_%d", uid)
	sku_ids, err := global.App.RDB.LRange(ctx, historyKey, 0, 4).Result()
	if err != nil {
		return nil, err
	}

	var NewSku model.GoodsSKU
	goods_list := make([]model.GoodsSKU, len(sku_ids))

	for i, sku_id := range sku_ids {
		global.App.DB.Raw("select id, name, image, price, unite from tb_goods_sku where id = ?", sku_id).Find(&NewSku)
		goods_list[i] = NewSku
	}
	return goods_list, nil
}

func ToUserCenterInfo(ctx *gin.Context) { // 显示用户中心-个人信息
	uid := ctx.GetInt("uid")
	address, phone := getDefaultAddress(uid)

	// 使用redis存储和获取历史浏览记录
	goods_list, err := getHistoryGoodList(ctx, uid)
	if err != nil {
		global.App.Log.Error(err.Error())
		ctx.HTML(http.StatusOK, "/ttsx/user/user_center_info.html", map[string]string{"errMsg": "获取用户历史浏览记录失败"})
		return
	}
	global.App.Log.Sugar().Infof("uid: %d, goods_list: %v", uid, goods_list)
	ctx.HTML(http.StatusOK, "user/user_center_info.html", map[string]interface{}{
		"Name":     ctx.GetString("username"),
		"IsActive": ctx.GetBool("IsActive"),
		"Phone":    phone,
		"Address":  strings.Split(address, " ")[0],
		"GoodList": goods_list,
	})
}

func ToUserCenterOrder(ctx *gin.Context) { // 显示用户中心-全部订单
	// 从上下文中获取uid,username
	uid := ctx.GetInt("uid")
	username := ctx.GetString("username")
	IsActive := ctx.GetBool("IsActive")

	// 获取页码
	pageIndex := utils.StrToInt(ctx.Param("page"))

	// 根据 uid 查询 order_info
	var count int64
	global.App.DB.Model(&model.OrderInfo{}).Where("user_id = ?", uid).Count(&count)
	global.App.Log.Sugar().Infof("Count: %d", count)

	/*  分页显示订单列表  */
	// 定义每一页显示的个数
	pageSize := 2

	// 计算需要的总页数
	pageCount := int(math.Ceil(float64(count) / float64(pageSize)))
	global.App.Log.Sugar().Infof("pageCount: %d", pageCount)

	// 根据 总页数 和 请求的页码 生成分页列表
	pages := utils.PageTool(int(pageCount), pageIndex)
	global.App.Log.Sugar().Infof("pages: %v", pages)

	// 获取上一页和下一页
	startPage := pageIndex - 1
	if startPage <= 1 {
		startPage = 1
	}

	nextPage := pageIndex + 1
	if nextPage > pageCount {
		nextPage = pageCount
	}

	// 计算偏移量
	offset := (pageIndex - 1) * pageSize

	// 查询 order_info表
	var newOrderInfos []model.OrderInfo
	global.App.DB.Where("user_id = ?", uid).Offset(offset).Limit(pageSize).Order("created_at").Find(&newOrderInfos)
	global.App.Log.Sugar().Infof("uid: %d, newOrderInfos: %v", uid, newOrderInfos)

	newOrderbuff := make(map[int]interface{}, len(newOrderInfos))
	// 遍历 newOrderInfos
	for _, v := range newOrderInfos {
		// 判断订单状态
		var orderStatus string
		switch v.OrderStatus {
		case 1:
			orderStatus = "待支付"
		case 2:
			orderStatus = "待发货"
		case 3:
			orderStatus = "待收货"
		case 4:
			orderStatus = "待评价"
		case 5:
			orderStatus = "已完成"
		default:
			orderStatus = "待支付"
		}

		var newOrderGoods []map[string]interface{}
		global.App.DB.Model(&model.OrderGoods{}).
			Select("tb_order_goods.count", "tb_goods_sku.name", "tb_goods_sku.price", "tb_goods_sku.unite", "tb_goods_sku.image").
			Joins("left join tb_goods_sku on tb_goods_sku.id = tb_order_goods.goods_sku_id").
			Where("tb_order_goods.order_info_id = ?", v.OrderId).
			Scan(&newOrderGoods)
		global.App.Log.Sugar().Infof("uid: %d, newOrderGoods: %v", uid, newOrderGoods)

		newOrderbuff[v.OrderId] = map[string]interface{}{
			"Total_price": fmt.Sprintf("%.2f", v.TotalPrice.InexactFloat64()+v.TransitPrice.InexactFloat64()),
			"OrderStatus": orderStatus,
			"OrderGoods":  newOrderGoods,
			"OrderInfo":   v,
		}
	}
	global.App.Log.Sugar().Infof("uid: %d, newOrderbuff: %v", uid, newOrderbuff)

	ctx.HTML(http.StatusOK, "user/user_center_order.html", map[string]interface{}{
		"Name":      username,
		"IsActive":  IsActive,
		"Pages":     pages,
		"PageIndex": pageIndex,
		"StartPage": startPage,
		"NextPage":  nextPage,
		"Orderbuff": newOrderbuff,
	})
}

func ToUserCenterSite(ctx *gin.Context) { // 显示用户中心-收货地址
	// 从上下文中获取uid,username
	uid := ctx.GetInt("uid")
	username := ctx.GetString("username")
	IsActive := ctx.GetBool("IsActive")

	defaultAddr, _ := getDefaultAddress(uid)
	global.App.Log.Sugar().Infof("%q", map[string]string{"user": username, "address": defaultAddr})

	ctx.HTML(http.StatusOK, "user/user_center_site.html", map[string]interface{}{
		"Name":     username,
		"IsActive": IsActive,
		"address":  defaultAddr,
	})
}

func DoUserCenterSite(ctx *gin.Context) { // 提交收货地址信息
	// 从上下文中获取uid
	uid := ctx.GetInt("uid")

	// 获取前端数据
	receiver := ctx.PostForm("receiver")
	address := ctx.PostForm("addr")
	mobile := ctx.PostForm("mobile")
	zipcode := ctx.PostForm("zipcode")

	// 校验数据
	if receiver == "" || address == "" || mobile == "" {
		ctx.HTML(http.StatusOK, "user/user_center_site.html", map[string]string{"errMsg": "提交的收件地址信息不完整"})
		return
	}

	reg, _ := regexp.Compile("^1[3|4|5|7|8][0-9]{9}$")
	phone := string(reg.Find([]byte(mobile)))
	if phone == "" || len(phone) != 11 {
		ctx.HTML(http.StatusOK, "user/user_center_site.html", map[string]string{"errMsg": "收件人手机号码格式错误"})
		return
	}

	// 查询是否有默认地址
	defaultAddr, _ := getDefaultAddress(uid)
	hasDefault := false
	if defaultAddr == "Null" {
		hasDefault = true
	}

	// 创建数据
	ret := global.App.DB.Create(&model.Address{
		User_Id:   uid,
		Receiver:  receiver,
		Addr:      address,
		Phone:     phone,
		Zipcode:   zipcode,
		Isdefault: hasDefault,
	})
	if ret.RowsAffected == 0 {
		global.App.Log.Error(ret.Error.Error())
		ctx.HTML(http.StatusOK, "user/user_center_site.html", map[string]string{"errMsg": "新增用户收件地址出现错误"})
		return
	}
	global.App.Log.Sugar().Infof("uid:%d, 新增地址信息成功", uid)
	ctx.Redirect(http.StatusFound, "/ttsx/user/user_center_site")
}
